<?php
namespace  App\Http\Controllers\Radius;
use  App\Http\Controllers\Controller;

use App\Order;
use App\Rad_heart_beat;
use App\Rad_user;
use App\Rad_user_account;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_account;
use App\Rad_merge_data;
use DB;
use App\Rad_manage_discount;
use App\Rad_order;
use App\Line;
use App\Agent;
use App\Teamqq;

use App\Manage_order_recode;
use App\Discount;
use App\Manage_login_log;
use Redis;
use App\Terrace;
use App\Http\Controllers\Radius\ModuleController;
use App\Http\Controllers\Radius\AdminController;
use Illuminate\Support\Facades\Crypt;
use App\Common\MyCrypt;
class UserController extends Controller
{


    private static $_ch;
    var $redis_;
    var $module;
    var $mycrypt;

    function __construct()
    {

        $this->module = new ModuleController();
        $this->redis_ = null;
        $this->mycrypt = new MyCrypt();

    }


    function __destruct()
    {
        if($this->redis_ != null) {
            $this->redis_->close();
        }
    }


    static function connectRedis()
    {
        $redis_ = new Redis();
        $redis_->connect("127.0.0.1", "6379");
        return $redis_;
    }


    /**
     *
     * 数据更新 每天删除用户金额
     */

    public function updateData()
    {
        $users = Rad_users::all()->toArray();

        foreach($users as $value)
        {
            $radreply = Radreply::where('username',$value['username'])->get()->toArray();
            if(empty($radreply))
            {
                $param['username'] = $value['username'];
                $param['attribute'] = 'Mikrotik-Rate-Limit';
                $param['op'] = '=';
                $param['value'] = '2048k/2048k';

                $id = Radreply::insertGetId($param);

                if($id)
                {
                    echo '------------------'.$value['username'].'-----------上下行'.$param['value'].'--------插入成功';
                }
            }
        }

    }






    //可以指定前缀   生成用户ID
    static function createUuid($prefix = "")
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8) . '-';
        $uuid .= substr($str,8,4) . '-';
        $uuid .= substr($str,12,4) . '-';
        $uuid .= substr($str,16,4) . '-';
        $uuid .= substr($str,20,12);
        return $prefix . $uuid;
    }


    /**
     * @param Request $request
     * parm username  用户名
     * param password  密码
     * return array()
     */
    public function createUser(Request $request)
    {
        $where = [];
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') && !empty($request->input('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $where['username'] = $request->input('username');

        //  密码
        if(!$request->has('password') &&  !empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $where['password'] = $request->input('password');

        $user = Rad_user::where($where)->get()->toArray();

        if(!empty($user))
        {
            self::ShowError(ErrorDefine::USER_IS_EXIST);
            return;
        }
        $ret = Rad_user::insert($where);
        $user = Rad_user::where($where)->first();
        $token = md5($user->user_id.'niumokeji'.time());
        $user->token = $token;
        $user->save();

        return self::ShowMessage();


    }


    /**
     * 代理管理员登录
     * param name(用户名)
     * param  password
     * return array() 用户信息
     */
    
    public function login(Request $request)
    {

        $manage = new  Manage_login_log();
        $manage->ip = '';
        $manage->status = 0;

        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if($request->has('ip') || !empty($request->input('ip')) )
        {
            $manage->ip = $request->input('ip');
        }

        $where = [];
        //  名称
        if(!$request->has('username') || empty($request->input('username')) )
        {
            $manage->save();
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $where['username'] = $request->input('username');
        $manage->username = $request->input('username');

        //  密码
        if(!$request->has('password') || empty($request->input('password')))
        {
            $manage->save();
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $password = $request->input('password');
        $manage->password = $request->input('password');


        $user = Rad_manage::where($where)->first();


        if($user == NULL)
        {
            $manage->save();
            self::ShowError(ErrorDefine::ACCOUNT_NOT_EXIST);
            return;
        }


        if($password != explode(',',$this->mycrypt->decrypt($user->password))[1])
        {
            $manage->save();
            self::ShowError(ErrorDefine::ACCOUNT_OR_PASSOERD_DIE);
            return;
        }


        $manage->status = 1;
        $manage->user_id = $user->manage_id;
        $manage->save();
        //  token 更新
        $token = md5($user->manage_id.'niumokeji'.time());
        $user->token = $token;

        $user->save();

        $qq ='';
        $res = Teamqq::where('manage_id',$user->manage_id)->first();
        if($res)
        {
            $qq = $res->qq;
        }

        $info = [];
        $info['qq'] = $qq;
        $info['token'] = $token;
        $info['manage_id'] = $user->manage_id;
        $info['username'] = $user->username;
        $info['balance'] = $user->balance;
        $info['level'] = $user->level;


        $data = array(
            'token'=>$token,
            'qq'=>$qq,
            'info'=>$info
        );

        return self::ShowMessage($data);


    }

    /**
     * 退出
     * param user_id
     * return array()
     */

    public function logout(Request $request)
    {

        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        $user = Rad_manage::where('token',$token)->first();
        $user->token = '';
        $user->save();

        return self::ShowMessage();

    }


    /**
     * @param Request $request
     * 用户详情
     */
    public function getUserInfo(Request $request)
    {
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $users = self::getTokenById($token);


        if(empty($users))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $user_id =  $users[0]['manage_id'];


        $info = Rad_manage::find($user_id);

        $province ='';
        $province = self::getAreaList();
        $data['line'] = $province;
        $data['info'] = $info;


        return self::ShowMessage($data);

    }


    public function getAreaList()
    {

        $province = Line::where('enable_flag','1')->distinct()->get(['province'])->toArray();

        foreach($province as $key=>&$value)
        {
            $line = Line::where('enable_flag','1')->where('province',$value['province'])->get(['province','city','carrieroperator','ip','niumoip'])->toArray();
            $value['city'] = $line;
        }

        return $province;
    }


    /**
     * @param Request $request
     * @return bool|void
     * 检测用户名
     */

    public function checkUserName(Request $request)
    {
        if(!$request->has('username') && empty($request->input('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = $request->input('username');
        $ret = Radcheck::where('username',$username)->get()->toArray();

        $data = [];
        if(!empty($ret))
        {
            $data['tag'] ='error';
        }else{
            $data['tag']='success';
        }

        return self::ShowMessage($data);
    }




    /**
     * @param Request $request
     * 管理员优惠列表
     */
    public function getManageInfo(Request $request)
    {

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');
        //   获取用户ID
        $user = self::getTokenById($token);
        if(!$user)
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }

        $manage_id=  $user[0]['manage_id'];


        $terrace = [];

        $manage_list = [];

        switch($user[0]['level'])
        {
            case 2:
                $manage_list =  Rad_manage::get(['manage_id', 'username']);
                $terrace =  Terrace::get(['id', 'terrace_name']);break;
            case 4:
                $manage_list =  Rad_manage::where('belong_manage',$manage_id)->get(['manage_id', 'username']);break;
        }


        $discount = Rad_manage::where('manage_id',$manage_id)->get(['middle-day','middle-week','middle-month','height-day','height-week','height-month']);


        if(!empty($discount)){
            $discount = $discount[0];
        }

        $data = array(
            'discount'=>$discount,
            'list'=>$manage_list,
            'terrace'=>$terrace,
        );

        return self::ShowMessage($data);
    }



    /**
     * @param Request $request
     * 获取账号列表
     */
    public function getAccountList(Request $request)
    {


        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);


        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $page_no = 0;
        $page_size =20;
        $username = '';
        $end_date = date('Y-m-d H:i:s',time());
        $start_date = '1970-01-01 08:00:00';




        $count = 0;
        $user_id = '';

        $result = [];


        $sql ="select user_id as id,username,password,qq,mobile,con_max as connect_num,created_at,account_type,expired_at,manage_id,set_meal_type,terrace_id,remark from users ";
        $sql_count = "select count(user_id) as num  from users";

        if($request->input('page_no'))
        {
            $page_no  = $request->input('page_no');
            if($page_no){
                $page_no = $page_no - 1;
                if(is_numeric($page_no)){
                    if($page_no<0){
                        $page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $page_size = $request->input('page_size');
            if($page_size){
                if($page_size <=0 ){
                    $page_size =  20;
                }
            }
        }


        // 查询时间
        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $end_date = $request->input('end_date');
        }




        $sql .=" where  created_at < '{$end_date}'";
        $sql_count .=" where  created_at < '{$end_date}'";

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $start_date = $request->input('start_date');
        }

        $sql .=" and  created_at > '{$start_date}'";
        $sql_count .=" and  created_at > '{$start_date}'";


        if($request->has('username') && !empty($request->input('username')))
        {
			$username = trim($request->input('username'));
            $sql .=" and  CONCAT(username,mobile)   like '%{$username}%'";
            $sql_count .=" and  CONCAT(username,mobile)  like '%{$username}%'";
        }





        if($request->has('manage_name') && !empty($request->input('manage_name')))
        {
            $manage_name = $request->input('manage_name');

            $res = Rad_manage::where('username',$manage_name)->first();

            if($res)
            {
                $user_id = $res->manage_id;

                $sql .=" and manage_id ='{$user_id}' ";
                $sql_count .=" and  manage_id ='{$user_id}' ";
            }

            $ret = Terrace::where('terrace_name',$manage_name)->first();

            if($ret)
            {
                $terrace_id = $ret->id ;

                $sql .=" and terrace_id ='{$terrace_id}' ";
                $sql_count .=" and  terrace_id ='{$terrace_id}' ";
            }

        }




        if($request->has('account_type') && !empty($request->input('account_type')) && $request->input('account_type')!="undefined")
        {
            $account_type = $request->input('account_type');
            $sql .=" and  account_type ='{$account_type}' ";
            $sql_count .=" and  account_type ='{$account_type}' ";
        }


        $manage_id=  $user[0]['manage_id'];



        switch($user[0]['level'])
        {
            case 1:
                $sql .=" and manage_id ='{$manage_id}' ";
                $sql_count .=" and  manage_id ='{$manage_id}' ";
                break;
            case 3:
                $sql .=" and manage_id in($manage_id) ";
                $sql_count .="  and manage_id in($manage_id)";
                break;
            case 4:
                $sql .=" and manage_id in(select manage_id from manage where belong_manage = {$manage_id} ) ";
                $sql_count .="  and manage_id in(select manage_id from manage where  belong_manage = {$manage_id})";
                break;
        }


        if($request->has('expired_at') && !empty($request->input('expired_at')))
        {

            $expired_at = $request->input('expired_at');

            $expired_start= date('Y-m-d H:i:s',time());

            switch($expired_at)
            {
                case "未到期":$sql .= " and expired_at > '{$expired_start}' ";
                    $sql_count .= " and expired_at > '{$expired_start}' "; break;

                case "已到期":$sql .= " and expired_at < '{$expired_start}' ";
                    $sql_count .= " and expired_at < '{$expired_start}' ";break;

                case "近三天到期":
                    $expired_end = date('Y-m-d H:i:s',time()+86400*3);
                    $sql .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";
                    $sql_count .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";break;

                case "近七天到期":
                    $expired_end = date('Y-m-d H:i:s',time()+86400*7);
                    $sql .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";
                    $sql_count .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";break;
                default:break;
            }

        }


        if($request->has('set_meal_type') && !empty($request->input('set_meal_type')))
        {
            $type = $request->input('set_meal_type');

            switch($type)
            {
                case 1: $sql .= " and set_meal_type = 1 ";$sql_count .= " and set_meal_type = 1 ";break;
                case 2: $sql .= " and set_meal_type = 2 ";$sql_count .= " and set_meal_type = 2 ";break;
                case 3: $sql .= " and set_meal_type = 3 ";$sql_count .= " and set_meal_type = 3 ";break;
                default:break;
            }

        }


        if($request->has('type') && !empty($request->input('type')))
        {
            if($request->has('sort_name') && !empty($request->input('sort_name')))
            {
                $sort_name= $request->input('sort_name');
                $sort_value= $request->input('sort_value');

                $sql .= "order by $sort_name  $sort_value ,id desc";
            }

        }else{
            $sql .= "  order by id desc   ";
        }


        $level = $user[0]['level'];


        $no = $page_no*$page_size;
        $sql .= " limit $no,$page_size ";


        $arr = self::getSuperAdminData($sql,$sql_count);


        $users = $arr['users'];
        $count = $arr['count'];

        $page_total = ceil($count /$page_size);


        //   筛选类型

        $terrace_arr = [];
        $manage_arr = [];

        if($level == 2)
        {
            $terrace = Terrace::all()->toArray();
            foreach($terrace as $item)
            {
                $terrace_arr["{$item['id']}"] = $item['terrace_name'];
            }
        }


        if($level == 4 || $level == 2)
        {
            $manage = Rad_manage::all()->toArray();
            foreach($manage as $res)
            {

                $manage_arr["{$res['manage_id']}"] = $res['username'];
            }
        }

        foreach($users as $key=>&$value)
        {

            if(array_key_exists($value['terrace_id'], $terrace_arr)){
                $users[$key]['manage_name'] = $terrace_arr["{$value['terrace_id']}"];
            }



            if(array_key_exists($value['manage_id'], $manage_arr)){
                $users[$key]['manage_name'] = $manage_arr["{$value['manage_id']}"];
                $users[$key]['self'] =  ($value['manage_id'] == $manage_id ? 1:0);
            }



            if(strtotime($value['expired_at']) - time() >= 0)
            {

                if(strtotime($value['expired_at']) - time() < 86400*2)
                {
                    $users[$key]['time'] ='即将到期';
                    $users[$key]['expired'] =1;
                }else{
                    $users[$key]['time'] ='';
                    $users[$key]['expired'] =0;           //  到期标识   0  未到期
                }

            }else{

                $users[$key]['time'] ='已到期';
                $users[$key]['expired'] =2;           //  1 已到期
            }



            switch($value['set_meal_type'])
            {
//                case 1:$users[$key]['set_meal'] = '基础套餐';break;
                case 2:$users[$key]['set_meal'] = '基础套餐';break;
                case 3:$users[$key]['set_meal'] = '高级套餐';break;
            }

            $res = Radreply::where('username',$value['username'])->first();



            $value['value'] = '';
            if($res)
            {
                $value['value'] = $res->value;
            }
        }



        $data = array(
            'count'=>$count,
            'page_total'=>$page_total,

            'level'=>$level,
            'account'=>$users
        );


        return self::ShowMessage($data);

    }

    /**
     * @param $start_date
     * @param $end_date
     * @param $username
     * @param $orderbytype
     * @param $orderBy
     * @param $page_no
     * @param $page_size
     * @return array
     * 超级管理员获取数据
     */
    static function getSuperAdminData($sql,$sql_count)
    {


        $users = DB::connection('mysql_concent')->select("$sql");

        $count = DB::connection('mysql_concent')->select("$sql_count");

        $res = [];
        foreach($users as $key=>$value)
        {
            $res[$key]['id'] = $value->id;
            $res[$key]['username'] = $value->username;
            $res[$key]['password'] = $value->password;
            $res[$key]['connect_num'] = $value->connect_num;
            $res[$key]['created_at'] = $value->created_at;
            $res[$key]['account_type'] = $value->account_type;
            $res[$key]['expired_at'] = $value->expired_at;
            $res[$key]['manage_id'] = $value->manage_id;
            $res[$key]['set_meal_type'] = $value->set_meal_type;
            $res[$key]['terrace_id'] = $value->terrace_id;
            $res[$key]['remark'] = $value->remark;
            $res[$key]['qq'] = $value->qq;
            $res[$key]['mobile'] = $value->mobile;
        }
        $arr = array(
            'users'=>$res,
            'count'=>$count[0]->num
        );

        return $arr;

    }




    /**
     * 添加账号
     *param name 用户名
     *param password 密码
     *param date  天数
     *param type  类型
     *param concent_num 连接数
     *
     *
     * return array();
     */
    public function addAcouunt(Request $request)
    {

        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') && empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $username = trim($request->input('username'));


        //  密码
        if(!$request->has('password') && empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }

        $password =  trim($request->input('password'));



        //  账号类型
        if(!$request->has('account_type') && empty($request->input('account_type')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_TYPE_ONT_EXIST);
            return;
        }
        $account_type = $request->input('account_type');


        //  连接数
        if(!$request->has('concent_num') && empty($request->input('concent_num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $concent_num = $request->input('concent_num');

        //   检测连接数
        if($concent_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }


        //   用户token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }


        $token = $request->input('token');

        $users = self::getTokenById($token);

        if(empty($users))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        //    备注
        $remark = '';
        if($request->input('remark'))
        {
            $remark = trim($request->input('remark'));
        }

        //    agent.niumoip.com 平台标识
        $agent = 0;
        if($request->input('agent'))
        {
            $agent = $request->input('agent');
        }


        $manage = 0;
        if($request->input('manage'))
        {
            $manage = $request->input('manage');
        }

        //  订单号
        if(!$request->has('order_id') && empty($request->input('order_id')))
        {
            self::ShowError(ErrorDefine::ORDER_NO_NOT_EXIST);
            return;
        }
        $order_no = $request->input('order_id');

        $recode = [];
        // 参数获取
        if($users[0]['level'] == 2 || $users[0]['level'] ==3)
        {
            $recode['remark'] = $request->input('remark');               // 备注
            $recode['serial_number'] = $request->input('serial_number');        //  流水号
            $recode['origin_type'] = $request->input('origin_type');     //  来源类型
            $recode['pay_type'] = $request->input('pay_type');           //  支付类型
            $recode['order_price'] = $request->input('order_price');     //  实际金额
            $recode['username'] = $request->input('username');           //  用户名
            $recode['account_type'] = $request->input('account_type');   //  账户类型
            $recode['connect_num'] = $request->input('concent_num');     //  账户连接数
            $recode['contact_information'] = $request->input('contact_information');     //  账户连接数
            $recode['month'] = 1;                                        //  账户数量
        }



        if($account_type != '测试')
        {

            //   日期卡类型
            if(!$request->has('date_type') && empty($request->input('date_type')))
            {
                self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
                return;
            }
            $date_type = $request->input('date_type');


            //     开通时间
            if(!$request->has('date') && empty($request->input('date')))
            {
                self::ShowError(ErrorDefine::DATE_NOT_EXIST);
                return;
            }

            $date = $request->input('date');


            if($date<=0) {
                self::ShowError(ErrorDefine::INVALID_DATE);
                return;
            }

            // 价格
            if(!$request->has('price') && empty($request->input('price')))
            {
                self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
                return;
            }
            $price = $request->input('price');

        }else{


            //   二级代理 普通用户 免费测试号 配额检测
            if($users[0]['level'] != 2 && $users[0]['level'] != 3 )
            {
                if($concent_num > $users[0]['test_con_max_quota'] )
                {
                    self::ShowError(ErrorDefine::TEST_ACCOUNT_LESS);
                    return;
                }

                if($users[0]['test_con_max_quota'] <= 0 || $users[0]['test_con_max_quota'] <= 0)
                {
                    self::ShowError(ErrorDefine::TEST_ACCOUNT_MORE);
                    return;
                }

            }

        }

//           用户类型   1   是普通用户  暂时默认普通
        if(!$request->has('set-meal-type') && empty($request->input('set-meal-type')))
        {
            self::ShowError(ErrorDefine::USER_TYPE_NO_EXIST);
            return;
        }
        $set_meal_type = $request->input('set-meal-type');
        $recode['set_meal_type'] = $request->input('set-meal-type');
        switch($set_meal_type)
        {
            case 2:$vip = 1;$recode['set_meal_type_name'] = '基础套餐'; break;
            case 3:$vip = 2;$recode['set_meal_type_name'] = '高级套餐';break;
        }


        //   获取用户ID
        $manage_id =  $users[0]['manage_id'];
        $recode['manage_name'] = $users[0]['username'];
        $recode['manage_id'] = $users[0]['manage_id'];

        //   判断   余额是否支持开户
        if($account_type !='测试')
        {
            if( $users[0]['balance'] < $price)
            {
                return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
            }
        }

        //   检测用户名是否存在
        $user = Radcheck::where('username',$username)->get(['id','username'])->toArray();
        $radreply = Radreply::where('username',$username)->get()->toArray();


        if(!empty($user) && !empty($radreply))
        {
            self::ShowError(ErrorDefine::USER_IS_EXIST);
            return;
        }
        // 开户时间  测试一小时
        if($account_type !='测试') {
            switch ($date_type) {
                case '日':
                    $expired_at = time() + 86400 * $date * 1;$recode['days'] = $date * 1;
                    break;
                case '周':
                    $expired_at = time() + 86400 * $date * 7;$recode['days'] = $date * 7;
                    break;
                case '月':
                    $expired_at = time() + 86400 * $date * 30;$recode['days'] = $date * 30;
                    break;
            }
        }else{
            $expired_at = time()+3600;
        }


        //   到期时间
        $time = date("d M Y H:i:s ",$expired_at);
        $recode['expired_at'] = date('Y-m-d H:i:s',$expired_at);

//      添加用户
        $where = [];
        $where['username'] =$username;
        $where['value'] =$password;
        $where['attribute'] ='Cleartext-Password';
        $where['op'] =':=';

        $account_id = Radcheck::insertGetId($where);

        //   添加到期时间
        $arr = [];
        $arr['username'] =$username;
        $arr['attribute'] ='Expiration';
        $arr['op'] =':=';
        $arr['value'] = $time;

        Radcheck::insertGetId($arr);


        //   用户账号表
        $account = [];

        $account['manage_id'] = $manage_id;
        $account['user_id'] = $account_id;
        $account['username'] = $username;
        $account['password'] = $password;
        $account['terrace_id'] = 0;
        $account['con_max'] =$concent_num ;
        $account['created_at'] = date('Y-m-d H:i:s',time());
        $account['updated_at'] = date('Y-m-d H:i:s',time());
        $account['expired_at'] = date('Y-m-d H:i:s',$expired_at);
        $account['account_type'] = $account_type;
        $account['vip'] = $vip;
        $account['remark'] = $remark;
        $account['set_meal_type'] = $set_meal_type;     //  套餐类型  1：基础  2：初级  3：高级
        if($account_type !='测试')
        {
            $account['balance'] =0 ;
        }

        $ret = Rad_users::insertGetId($account);



        //   用户所属组  即连接数
        $group = Radgroupcheck::where('value',$concent_num)->get()->toArray();

//        // 为空  则添加组
        if(empty($group))
        {
            //   添加组
            $group_parm = [];
            $group_parm['groupname'] = 'c'.$concent_num;
            $group_parm['attribute'] = 'Simultaneous-Use';
            $group_parm['op'] = ':=';
            $group_parm['value'] = $concent_num;
            Radgroupcheck::insertGetId($group_parm);
            //   添加组的属性

            //  属性1
            $group_attribute1= [];
            $group_attribute1['groupname'] = 'c'.$concent_num;
            $group_attribute1['attribute'] = 'Auth-Type';
            $group_attribute1['op'] = ':=';
            $group_attribute1['value'] = 'Local';


            //  属性2
            $group_attribute2= [];
            $group_attribute2['groupname'] = 'c'.$concent_num;
            $group_attribute2['attribute'] = 'Service-Type';
            $group_attribute2['op'] = ':=';
            $group_attribute2['value'] = 'Framed-User';


            //  属性3
            $group_attribute3= [];
            $group_attribute3['groupname'] = 'c'.$concent_num;
            $group_attribute3['attribute'] = 'Framed-IP-Address';
            $group_attribute3['op'] = ':=';
            $group_attribute3['value'] = '255.255.255.255';

            $group_attribute4= [];
            $group_attribute4['groupname'] = 'c'.$concent_num;
            $group_attribute4['attribute'] = 'Framed-IP-Netmask';
            $group_attribute4['op'] = ':=';
            $group_attribute4['value'] = '255.255.255.0';

            Radgroupreply::insertGetId($group_attribute1);
            Radgroupreply::insertGetId($group_attribute2);
            Radgroupreply::insertGetId($group_attribute3);
            Radgroupreply::insertGetId($group_attribute4);
        }

        //   添加用户与组的对应关系
        $user_group = [];
        $user_group['username'] = $username;
        $user_group['groupname'] = 'c'.$concent_num;
        $user_group['priority'] = 1;
        Radusergroup::insertGetId($user_group);

        $param['username'] = $username;
        $param['attribute'] = 'Mikrotik-Rate-Limit';
        $param['op'] = '=';

        switch($set_meal_type)
        {
            case 1: $param['value'] = '512k/512k';break;
            case 2:  $param['value'] = '2048k/2048k';break;
            case 3: $param['value'] = '4096k/4096k';break;
        }
        $id = Radreply::insertGetId($param);



        //   订单信息

        $oder = [];
        if($account_type !='测试')
        {
            $order['balance'] = $users[0]['balance']-$price;
            $order['date'] =$date;
            $order['price'] =$price;
        }else{
            $order['balance'] = $users[0]['balance'];
            $order['date'] = 0;
            $order['price'] =0;
        }
        $order['account_type'] = $account_type;
        $order['connect_num'] =$concent_num;
        $order['user_id'] = $manage_id;                 //   用户id
        $order['to_user'] =$account_id;
        $order['order_no'] =$order_no;
        $order['pay_channel'] =2;                    //    支付标识   余额  2
        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());


        $id = Rad_order::insertGetId($order);
        if($id)
        {
            $orders = Rad_order::find($id);
            $orders->status = 1;
            $orders->save();
        }


        //   管理员开号记录
        try{
            if($users[0]['level'] == 2 || $users[0]['level'] ==3)
            {
                Manage_order_recode::insertGetId($recode);
            }
        }catch (\Exception $e){

        }


        if($account_type !='测试')
        {
            $user = Rad_manage::find($manage_id);
            $user->balance = $user->balance - $price;
            $user->save();
        }else{
            // 去除配额
            if($users[0]['level'] != 2 || $users[0]['level'] !=3 )
            {
                $user = Rad_manage::find($manage_id);
                $user->test_con_max_quota = $user->test_con_max_quota - $concent_num;
                $user->test_account_quota = $user->test_account_quota - 1;
                $user->save();
            }

        }

        return self::ShowMessage();

    }



    /**
     * @param Request $request
     * 续费
     */
    public function renewAccount(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') || empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = $request->input('username');

        //  密码
        if(!$request->has('password') || empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $password = $request->input('password');


        //  账号类型
        if(!$request->has('renew_type') || empty($request->input('renew_type')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }
        $renew_type = $request->input('renew_type');


        //  连接数
        if(!$request->has('connect_num') || empty($request->input('connect_num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $connect_num = $request->input('connect_num');

        //   检测连接数
        if($connect_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }


        //   用户token
        if(!$request->has('token')  || empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        if(!$request->has('renew_date') || empty($request->input('renew_date')) || is_int($request->input('renew_date')))
        {
            self::ShowError(ErrorDefine::DATE_NOT_EXIST);
            return;
        }
        $renew_date= $request->input('renew_date');

        if($renew_date<=0) {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }

        //  订单号
        if(!$request->has('order_id') || empty($request->input('order_id')))
        {
            self::ShowError(ErrorDefine::ORDER_NO_NOT_EXIST);
            return;
        }
        $order_no = $request->input('order_id');


        // 价格
        if(!$request->has('price') || empty($request->input('price')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $price = $request->input('price');


        //   获取用户ID
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        $manage_id =  $user[0]['manage_id'];

        if( $user[0]['balance'] < $price)
        {
            return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
        }


        switch ($renew_type) {
            case '日':
                $expired_at = time() + 86400 * $renew_date * 1;$date = $renew_date * 1;
                break;
            case '周':
                $expired_at = time() + 86400 * $renew_date * 7;$date = $renew_date * 7;
                break;
            case '月':
                $expired_at = time() + 86400 * $renew_date * 30;$date = $renew_date * 30;
                break;
        }

        $where = [];
        $where['username'] = $username;
        $where['attribute'] = 'Expiration';
        $where['op'] = ':=';


        $rad = Radcheck::where($where)->get();


        if(strtotime($rad[0]->value) > time())
        {
            $expired_at = strtotime($rad[0]->value) + $expired_at - time();
        }

        $time = date("d M Y H:i:s ",$expired_at);

        $rad[0]->value=$time;



        $where2 = [];

        $where2['username'] = $username;
        $ret = Rad_users::where($where2)->get();

        if($ret[0]->pid)
        {
            $rad_user = Rad_users::where('user_id',$ret[0]->pid)->first();
            $rad_user->total_consumption = $rad_user->total_consumption + $price;
            $rad_user->save();
        }else{
            $ret[0]->total_consumption = $ret[0]->total_consumption + $price;
        }

        $ret[0]->updated_at = date('Y-m-d H:i:s',time());
        $ret[0]->expired_at = date('Y-m-d H:i:s',$expired_at);

        $ret[0]->account_type = '付费';

        $ret[0]->save();
        $rad[0]->save();

        $oder = [];

        $order['balance'] = $user[0]['balance']-$price;
        $order['date'] =$renew_date;
        $order['price'] =$price;

        $order['account_type'] = '付费';
        $order['connect_num'] =$connect_num;
        $order['user_id'] = $manage_id;
        $order['status'] = 1;
        $order['order_no'] =$order_no;
        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());

        Rad_order::insertGetId($order);

        $user = Rad_manage::find($manage_id);

        $user->balance = $user->balance - $price;
        $user->save();



        $set_meal_type = $ret[0]->set_meal_type;
        switch ($set_meal_type)
        {
            case 2: $set_meal_type_name ='基础套餐';break;
            case 3: $set_meal_type_name ='高级套餐';break;
            default:$set_meal_type_name ='基础套餐';break;
        }


        //   管理员开号记录
        // 参数获取
        if($user->level == 2 || $user->level ==3)
        {

            try{
                $recode['serial_number'] = $request->input('serial_number');
                $recode['username'] = $request->input('username');
                $recode['origin_type'] = $request->input('origin_type');
                $recode['pay_type'] = $request->input('pay_type');
                $recode['remark'] = $request->input('remark');
                $recode['contact_information'] = $request->input('contact_information');
                $recode['month'] = 1;
                $recode['order_price'] = $request->input('order_price');
                $recode['set_meal_type'] = $set_meal_type;
                $recode['set_meal_type_name'] = $set_meal_type_name;
                $recode['manage_id'] = $manage_id;
                $recode['manage_name'] = $user->username;
                $recode['days'] = $date;
                $recode['account_type'] = '续费';
                $recode['connect_num'] = $connect_num;
                $recode['expired_at'] = date('Y-m-d H:i:s',$expired_at);

                Manage_order_recode::insert($recode);
            }catch (\Exception $exception)
            {

            }
        }


        return self::ShowMessage();

    }
    

    

    /**
     * @param Request $request
     * 更新账户信息
     */
	public function updateAcouunt(Request $request)
	{
		if(empty($request->all()))
		{
			self::ShowError(ErrorDefine::EMPTY_POST_DATA);
			return;
		}

		$where=  [];
		//  用户名
		if(!$request->has('username') && !empty($request->input('username')) )
		{
			self::ShowError(ErrorDefine::NAME_NOT_EXIST);
			return;
		}
		$where['username'] = trim($request->input('username'));


		// 密码
		if(!$request->has('password') && !empty($request->input('password')))
		{
			self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
			return;
		}

		$where['value'] = trim($request->input('password'));


		//  账号ID
		if(!$request->has('account_id') && !empty($request->input('account_id')))
		{
			self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);

		}
		$user_id = $request->input('account_id');



		$remark = '';
		if($request->has('remark'))
		{
			$remark = $request->input('remark');
		}
		$speed = '';

		//  限速的速度
		if($request->has('speed') && !empty($request->input('speed')))
		{
			$speed = $request->input('speed');
		}



		if($request->has('set-meal-type'))
		{
			$set_meal_type = $request->input('set-meal-type');
		}else{
			$users  = Rad_users::find($user_id);
			$set_meal_type = $users->set_meal_type;
		}


		// 获取用户信息
		$user = Rad_users::find($user_id)->toArray();

		//   检测新的用户名是否被使用
		$info = Radcheck::where('username',$where['username'])->get()->toArray();

		if(!empty($info))
		{
			if($user['username'] != $info[0]['username'])
			{
				self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
				return;
			}
		}
        $params = [];
		if($speed)
		{

			//  限速修改
			$radreply = Radreply::where('username',$user['username'])->where('attribute','Mikrotik-Rate-Limit')->first();
			if($radreply == NULL)
			{
                $params['username'] = $where['username'];
                $params['value'] = $speed;
                $params['attribute'] = 'Mikrotik-Rate-Limit';
                $params['op'] = '=';

                Radreply::insertGetId($params);
            }else{
                $radreply->username = $where['username'];
                $radreply->value = $speed;
                $radreply->save();
            }


		}



		//  更新用户表内用户信息
		$ret1 = Radcheck::where('username',$user['username'])->where('id',$user_id)->update($where);

		$ret2 = Radcheck::where('username',$user['username'])->where('attribute','=','Expiration')->update(['username'=>$where['username']]);

		// 更新用户组信息
		$ret3 = Radusergroup::where('username',$user['username'])->update(['username'=>$where['username']]);

		Rad_users::where('username',$user['username'])->where('user_id','=',$user_id)->update(['username'=>$where['username'],'password'=>$where['value'],'remark'=>$remark,'set_meal_type'=>$set_meal_type]);

		return self::ShowMessage();


	}





    /**
     * @param Request $request
     * 某一账户在线信息
     */
    public function getAccountOnlineInfo(Request $request)
    {
        $account_id  = $request->input('account_id');

        $user = Radcheck::find($account_id);

        $online = [];
        $result = DB::connection('mysql_concent')->select("SELECT * FROM radacct WHERE (acctstoptime IS  NULL AND UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +100  > UNIX_TIMESTAMP() ) and  username = '{$user->username}'");
        foreach($result as $key=>$value)
        {
            $online[$key]['radacctid'] = $value->radacctid;
            $online[$key]['acctsessionid'] = $value->acctsessionid;
            $online[$key]['username'] = $value->username;
            $online[$key]['calledstationid'] = $value->calledstationid;
            $online[$key]['framedipaddress'] = $value->framedipaddress;
            $online[$key]['acctstarttime'] = $value->acctstarttime;
            $online[$key]['nasipaddress'] = $value->nasipaddress;
        }

        $data=array(
            'online'=>$online
        );
        return self::ShowMessage($data);

    }

    /**
     * @param Request $request
     * 禁用用户
     */
    public function forbiddenAccount(Request $request)
    {

        $data =  $where = $request->all();

        $heart_beat = Rad_heart_beat::where('username',$data['user'])->first();
        if($heart_beat != NULL)
        {
            $heart_beat->delete();
        }

        $area = self::getCity($data['rosip']);

        $rosip = self::getRosIp($area,$data['rosip']);

        $data['rosip'] =$rosip;
        $data = http_build_query($data);


        $out = "GET http://121.196.202.198 HTTP/1.1\r\n";  // 通过POST方式发送数据
        $out .= "121.196.202.198\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
        $out .= "Content-length: ".strlen($data)."\r\n";
        $out .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:48.0) Gecko/20100101 Firefox/48.0"."\r\n";
        $out .= "Connection: close"."\r\n"."\r\n";    // 注意：此处有两个 \r\n

        $out .= $data."\r\n";   // 正文数据

        $fp = fsockopen("121.196.202.198", 17332, $errno, $errstr, 30);  // 创建socket客户端连接


        fwrite($fp, $out);    // 向服务器发送数据


//        while (!feof($fp)) {
            $status =  fgets($fp, 1280);    // 读取服务器响应的数据
//        }

        return self::ShowMessage($status);

    }

    /**
     * @param $ip
     * @return bool|mixed|string
     * 获取城市
     */
    static function getCity($ip)
    {
        if(empty($ip)){
            return '请输入IP地址';
        }
        $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
        if(empty($res)){ return false; }
        $jsonMatches = array();
        preg_match('#\{.+?\}#', $res, $jsonMatches);
        if(!isset($jsonMatches[0])){ return false; }
        $json = json_decode($jsonMatches[0], true);
        if(isset($json['ret']) && $json['ret'] == 1){
            $json['ip'] = $ip;
            unset($json['ret']);
        }else{
            return false;
        }
        return $json;
    }


    static function getRosIp($area,$ip)
    {

        $line = Line::where('province',$area['province'])->where('city',$area['city'])->where('enable_flag',1)->first();
        $service = $line->ip;
        $service_ip =  gethostbyname($service);

        if($service_ip != $ip)
        {
            $ip  = $service_ip;
        }

        return  $ip;

    }


    // 账号线路在线列表
	public function getOnlineList(Request $request)
	{


		$page_no = 0;
		$page_size=20;
		$username = '';
		$end_date = date('Y-m-d H:i:s');
		$start_date = '1970-01-01 08:00:00';
        $sort_name = 'num';
        $sort_value = 'desc';
        $pageNum = 1;

		if(!$request->has('token') && empty($request->input('token')))
		{
			self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
			return;
		}
		$token = $request->input('token');

		//   获取用户ID

		if($request->has('end_date') && !empty($request->input('end_date')))
		{
			$end_date = $request->input('end_date');
		}

		if($request->has('start_date') && !empty($request->input('start_date')))
		{
			$start_date = $request->input('start_date');
		}

		if($request->has('username') && !empty($request->input('username')))
		{
			$username = $request->input('username');
		}

        if (preg_match("/[\x7f-\xff]/", $username))
        {
            self::ShowError(ErrorDefine::INVALID_USERNAME);
            return;
        }

        if($request->has('sort_name') && !empty($request->input('sort_name')))
        {
            $sort_name = $request->input('sort_name');
        }

        if($request->has('sort_value') && !empty($request->input('sort_value')))
        {
            $sort_value = $request->input('sort_value');
        }

		if($request->input('page_no'))
		{
			$page_no  = $request->input('page_no');
			if($page_no){
				$page_no = $page_no - 1;
				if(is_numeric($page_no)){
					if($page_no<0){
						$page_no = 0;
					}
				}
			}
		}

		if($request->input('page_size'))
		{
			$page_size = $request->input('page_size');
			if($page_size){
				if($page_size <=0 ){
					$page_size =  20;
				}
			}
		}


		$user = self::getTokenById($token);

		if(empty($user))
		{
			self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}


		$user_id = $user[0]['manage_id'];

		$level = $user[0]['level'];
        $pageNum = $page_no;
        $page_no = $page_no*$page_size;

		$time = date('Y-m-d H:i:s',time());

		switch($level)
		{
			case 1:
                $data = self::getUesrOnlineAccountData($user_id,$username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value);break;
			case 3:
                $data = self::getUesrOnlineAccountData($user_id,$username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value);break;
			case 2:
                $data = self::getSuperOnlineAccountData($username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value);break;
            case 4:
                $data = self::getAgentOnlineAccountData($user_id,$username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value);break;

        }

        $count = $data['num'];
        $result = $data['result'];
        $number = $data['number'];

		$total = ceil($count/$page_size);


		$data=array(
			'total'=>$number,
			'pageNum'=>$pageNum,
			'page_total'=>$total,
			'online'=>$result
		);
		return self::ShowMessage($data);

	}



    static function getUesrOnlineAccountData($user_id,$username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value)
    {


        $sql = "select radacct.radacctid,radacct.acctsessionid,radacct.acctstarttime,radacct.username,count(*) as num
                ,users.user_id from radacct left join users on radacct.username = users.username where radacct.username like '%{$username}%'
                and radacct.username in (select username from users where manage_id = $user_id)
                and radacct.acctstarttime > '$start_date'
                and radacct.acctstarttime < '$end_date' and radacct.acctstoptime is null
                and UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +10000000000 > UNIX_TIMESTAMP()
                group by radacct.username ORDER BY $sort_name $sort_value limit $page_no,$page_size ";



        $sql2 = "select count(username) as number,count( DISTINCT username) as num from radacct where username like '%{$username}%'
                 and username in (select username from users where manage_id = $user_id)
                 and acctstarttime > '{$start_date}'
                 and acctstarttime < '$end_date' and acctstoptime is null
                 and UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +10000000000000 > UNIX_TIMESTAMP()";

        $user_number = DB::connection('mysql_concent')->select("$sql2");
        $users = DB::connection('mysql_concent')->select("$sql");

        $data = [
            'num'=>$user_number[0]->num,
            'number'=>$user_number[0]->number,
            'result'=>$users
        ];
        return $data;

    }



    static function getSuperOnlineAccountData($username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value)
    {


        $sql = "select radacct.radacctid,radacct.acctsessionid,radacct.acctstarttime,radacct.username,count(*) as num
                ,users.user_id from radacct left join users on radacct.username = users.username where radacct.username like '%{$username}%'
                and radacct.acctstarttime > '$start_date'
                and radacct.acctstarttime < '$end_date' and radacct.acctstoptime is null
                and UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +10000000000 > UNIX_TIMESTAMP()
                group by radacct.username ORDER BY $sort_name $sort_value limit $page_no,$page_size ";

        $sql2 = "select count(username) as number ,count( DISTINCT username) as num from radacct where username like '%{$username}%' and acctstarttime > '{$start_date}'
                 and acctstarttime < '$end_date' and acctstoptime is null
                 and UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +100000000000 > UNIX_TIMESTAMP()";

        $user_number = DB::connection('mysql_concent')->select("$sql2");
        $users = DB::connection('mysql_concent')->select("$sql");

        $data = [
            'num'=>$user_number[0]->num,
            'number'=>$user_number[0]->number,
            'result'=>$users
        ];

        return $data;
    }


    static function getAgentOnlineAccountData($user_id,$username,$start_date,$end_date,$page_no,$page_size,$sort_name,$sort_value)
    {

        $sql = "select radacct.radacctid,radacct.acctsessionid,radacct.acctstarttime,radacct.username,count(*) as num
                ,users.user_id from radacct left join users on radacct.username = users.username where
                users.manage_id in(select manage_id from manage where  belong_manage = {$user_id})
                and radacct.username like '%{$username}%'
                and radacct.acctstarttime > '$start_date'
                and radacct.acctstarttime < '$end_date' and radacct.acctstoptime is null
                and UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +10000000000 > UNIX_TIMESTAMP()
                group by radacct.username ORDER BY $sort_name $sort_value limit $page_no,$page_size ";


        $sql2 = "select count(radacct.username) as number ,count( DISTINCT radacct.username) as num from radacct
                 left join users on radacct.username = users.username where
                 users.manage_id in(select manage_id from manage where  belong_manage = {$user_id})
                 and radacct.username like '%{$username}%' and radacct.acctstarttime > '{$start_date}'
                 and radacct.acctstarttime < '$end_date' and radacct.acctstoptime is null
                 and UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +100000000000 > UNIX_TIMESTAMP()";
        $user_number = DB::connection('mysql_concent')->select("$sql2");
        $users = DB::connection('mysql_concent')->select("$sql");

        $data = [
            'num'=>$user_number[0]->num,
            'number'=>$user_number[0]->number,
            'result'=>$users
        ];

        return $data;
    }




    /**
     * @param Request $request
     * 限速
     */
    public function limitSpeed(Request $request)
    {
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        $user = self::getTokenById($token);

        if(empty($user))
        {
            self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
            return;
        }

        $user_id = $user[0]['manage_id'];



        if(!$request->has('on-line') || empty($request->input('on-line')))
        {
            self::ShowError(ErrorDefine::UP_LINE_NOT_EXIST);
            return;
        }
        $on_line = $request->input('on-line');

        if(!$request->has('next-line') || empty($request->input('next-line')))
        {
            self::ShowError(ErrorDefine::NEXT_LINE_NOT_EXIST);
            return;
        }

        $next_line = $request->input('next-line');

        if(!$request->has('account_id') || empty($request->input('account_id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
            return;
        }

        $account_id = $request->input('account_id');


//        nm99(username)	Mikrotik-Rate-Limit(attribute)	=(op)	64k/64k(value)

        $users = Rad_users::find($account_id);

        $param = [];

        $ret = Radreply::where('username',$users->username)->where('attribute','Mikrotik-Rate-Limit')->first();

        if(empty($ret))
        {
            $param['username'] = $users->username;
            $param['attribute'] = 'Mikrotik-Rate-Limit';
            $param['op'] = '=';
            $param['value'] = $on_line.'k/'.$next_line.'k';

            Radreply::insertGetId($param);


        }else{
            $ret->value =$on_line.'k/'.$next_line.'k';
            $ret->save();
        }

        return self::ShowMessage();

    }


    
    /**
 * @param Request $request
 * 获取用户订单列表
     *
 */
    public function getBillList(Request $request)
    {
        $end_date = date('Y-m-d H:i:s');
        $start_date = date('Y-m-01');
        $page_no = 0;
        $page_size = 20;

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);

        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $end_date = $request->input('end_date');
        }

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $start_date = $request->input('start_date');
        }


        if($request->input('page_no'))
        {
            $page_no  = $request->input('page_no');
            if($page_no){
                $page_no = $page_no - 1;
                if(is_numeric($page_no)){
                    if($page_no<0){
                        $page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $page_size = $request->input('page_size');
            if($page_size){
                if($page_size <=0 ){
                    $page_size =  20;
                }
            }
        }



        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $user_id =  $user[0]['manage_id'];
        $data = [];

        $orders = Rad_order::where('user_id',$user_id)->where('status',1)->where('account_type','付费')->where('created_at','>',$start_date)->where('created_at','<',$end_date)->orderBy('created_at','desc')->orderBy('balance','asc')->offset($page_size*$page_no)->limit($page_size)->get(['order_no','date','account_type','balance','price','created_at'])->toArray();
        $count = Rad_order::where('user_id',$user_id)->where('status',1)->where('account_type','付费')->where('created_at','>',$start_date)->where('created_at','<',$end_date)->orderBy('created_at','desc')->count();

        return  self::ShowData($orders,$count);


    }


    /**
     *用户线路删除
     */
    public function deleteAccountLine(Request $request)
    {
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        $user = self::getTokenById($token);

        $manage_id = $user[0]['manage_id'];
        $level= $user[0]['level'];


        $id  = $request->input('id');

        $id = explode(',',$id);

        $month = count($id);

        if($month > 1)
        {
            $account_type = '批量删除';
        }else{
            $account_type = '账户删除';
        }

        //   管理员开号记录
        try{
            $recode = [];
            if($level == 2 || $level == 3 )
            {

                $set_meal = Rad_user::whereIn('user_id',$id)->distinct('set_meal_type')->get(['set_meal_type'])->toArray();
                $name = Rad_user::whereIn('user_id',$id)->get(['username'])->toArray();
                $connect_num = Rad_user::whereIn('user_id',$id)->sum('con_max');
                $set_meal_type= '';
                $set_meal_type_name = '';
                $username = '';
                foreach ($set_meal as $res)
                {
                    $set_meal_type = $set_meal_type.','.$res['set_meal_type'];

                    if($res['set_meal_type'] == 2)
                    {
                        $meal_type_name = '基础套餐';
                    }else{
                        $meal_type_name = '高级套餐';
                    }
                    $set_meal_type_name = $set_meal_type_name.','.$meal_type_name;
                }



                foreach ($name as $ret)
                {
                    $username = $username.','.$ret['username'];
                }

                $set_meal_type = trim($set_meal_type,',');
                $set_meal_type_name = trim($set_meal_type_name,',');
                $username = trim($username,',');


                $account = Manage_order_recode::where('username',$username)->where('status',1)->first();
                if($account != NULL)
                {
                    $account->status = 2;
                    $account->save();
                }


                $ret = AdminController::serialNumber();

                $recode['serial_number'] = $ret;
                $recode['username'] = $username;
                $recode['origin_type'] = '';
                $recode['pay_type'] = '';
                $recode['remark'] = $request->input('remark');
                $recode['contact_information'] = '';
                $recode['month'] = $month;
                $recode['order_price'] = 0;
                $recode['set_meal_type'] = $set_meal_type;
                $recode['set_meal_type_name'] = $set_meal_type_name;
                $recode['manage_id'] = $manage_id;
                $recode['manage_name'] = $user[0]['username'];
                $recode['days'] = 0;
                $recode['status'] = 2;
                $recode['account_type'] = $account_type;
                $recode['connect_num'] = $connect_num;
                $recode['expired_at'] = date('Y-m-d H:i:s',time());
                $ret = Manage_order_recode::insert($recode);

            }
        }catch (\Exception $e)
        {

        }

        foreach($id as $value)
        {

            if($level == 2)
            {
                $this->module->DeleteAccount($value);

            }else{
                $users = Rad_users::find($value);

                if($users->manage_id == $manage_id)
                {
                    $this->module->DeleteAccount($value);
                }
            }

        }


        return self::ShowMessage('SUCCESS');


    }
    
    

    
    
    /**
     * @param $token
     * @return mixed
     * token   换取 用ID
     */
    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }




}


